﻿using Mengsk.ProxyDelivery.Domain;
using Mengsk.ProxyDelivery.Service;
using Mengsk.ProxyDelivery.Service.Spider;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace Mengsk.ProxyDelivery.GoodsSpider.UI
{
    /// <summary>
    /// Interaction logic for GoodsSpiderOneUC.xaml
    /// </summary>
    public partial class GoodsSpiderOneUC : UserControl
    {
        public static readonly DependencyProperty CountProperty = DependencyProperty.Register("Count", typeof(int), typeof(GoodsSpiderOneUC));

        public string ThreadNumber { get; set; }

        private bool IsStop { get; set; }

        public bool IsRunning { get; private set; }

        public int Count { get { return (int)this.GetValue(CountProperty); } set { this.SetValue(CountProperty, value); } }

        private SpiderBase spider;

        public GoodsSpiderOneUC()
        {
            InitializeComponent();
        }

        private void AttachEvent(SpiderBase spider)
        {
            this.spider = spider;
            this.spider.Start += spider_Start;
            this.spider.Stop += spider_Stop;
            this.spider.Message += spider_Message;
            this.spider.Progress += spider_Progress;
        }

        void spider_Stop(object sender, SpiderStopEventArgs e)
        {
            this.Dispatcher.Invoke(new Action(() => this.tbIsRunning.Text = "已停止"));
            if (this.spider.ErrorMessage.Length != 0)
            {
                this.AppenMessage("有错误发生，注意查看");
            }

            this.Dispatcher.Invoke(new Action(() =>
            {
                bool error = this.spider.ErrorMessage.Length > 0;
                this.tbError.Background = error ? Brushes.Red : null;
                this.tbError.Text = error ? "错误" : "";
            }));
        }

        void spider_Start(object sender, SpiderStartEventArgs e)
        {
            this.Dispatcher.Invoke(new Action(() => this.tbIsRunning.Text = "运行中"));
        }

        private void Dettachevent()
        {
            this.spider.Start -= spider_Start;
            this.spider.Stop -= spider_Stop;
            this.spider.Message -= spider_Message;
            this.spider.Progress -= spider_Progress;
        }

        void spider_Progress(object sender, SpiderProgressEventArgs e)
        {
            this.Dispatcher.Invoke(new Action(() =>
            {
                this.pbProgress.Value = e.Current * 1.0 / e.Total;
                this.tbDownloaded.Text = "已经下载：" + e.Current;
            }));
        }

        void spider_Message(object sender, SpiderMessageEventArgs e)
        {
            this.AppenMessage(e.Message);
        }

        private void AppenMessage(string message)
        {
            this.Dispatcher.Invoke(new Action(() =>
            {
                if (this.tbMessage.LineCount > 10000)
                {
                    this.tbMessage.Clear();
                }
                this.tbMessage.AppendText(DateTime.Now + ":" + message + Environment.NewLine);
                this.tbMessage.ScrollToEnd();
            }));
        }

        internal Task StartSycVendors(SpiderBase spider, VendorService vendorService)
        {
            return Task.Factory.StartNew(() => InvokeAction(spider, new Action(() => spider.SycVendor(vendorService))));
        }

        internal Task StartSycGoodss(SpiderBase spider, Mengsk.ProxyDelivery.Domain.Vendor[] vendors, ShoesService shoesService)
        {
            this.Count = vendors.Length;
            return Task.Factory.StartNew(() => InvokeAction(spider, new Action(() => spider.SycGoodss(vendors, shoesService))));
        }

        public void Stop()
        {
            if (this.spider != null)
            {
                this.spider.StopSyc();
            }
        }

        private void InvokeAction(SpiderBase spider, Action action)
        {
            try
            {
                this.AttachEvent(spider);
                Thread.Sleep(1000);
                action();
            }
            finally
            {
                this.Dettachevent();
            }
        }

        private void btnViewError_Click(object sender, RoutedEventArgs e)
        {
            if (this.spider == null || this.spider.ErrorMessage.Length == 0)
            {
                MessageBox.Show("没有错误信息");
                return;
            }
            ErrorViewWindow evw = new ErrorViewWindow { ErrorMessage = this.spider.ErrorMessage.ToString() };
            evw.ShowDialog();
        }
    }
}
